package com.ruyiadmin.springboot.common_infrastructure.components.system;

import com.ruyiadmin.springboot.common_infrastructure.constants.framework.Keywords;
import com.ruyiadmin.springboot.common_infrastructure.constants.system.ExceptionMessage;
import com.ruyiadmin.springboot.common_infrastructure.properties.SystemConfig;
import com.ruyiadmin.springboot.common_infrastructure.exceptions.RuYiAdminCustomException;
import com.ruyiadmin.springboot.common_infrastructure.utilities.framework_util.RuYiRsaUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * <p>
 * Token工具类
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-07-20
 */
@Component
@EnableConfigurationProperties({SystemConfig.class})
@RequiredArgsConstructor
public class RuYiTokenContext {

    //region 工具类私有属性

    private final SystemConfig systemConfig;

    //endregion

    //region 获取用户Token

    /**
     * 获取用户Token
     *
     * @return 用户Token
     * @throws Exception 异常信息
     */
    public String getToken() throws Exception {

        //获取请求url,ip,httpMethod
        HttpServletRequest request = ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        String token = request.getHeader(Keywords.TOKEN);

        if (StringUtils.isEmpty(token)) {
            throw new RuYiAdminCustomException(ExceptionMessage.InvalidTokenExceptionMessage);
        }

        token = RuYiRsaUtil.decrypt(token, this.systemConfig.getRsaPrivateKey());
        token = StringUtils.split(token, "^")[0];

        return token;
    }

    //endregion

    //region 获取口令Salt

    /**
     * <p>
     * 获取用户口令Salt
     * </p>
     *
     * @return 用户Token
     */
    public String getSalt() throws Exception {

        //获取请求url,ip,httpMethod
        HttpServletRequest request = ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        String tokenSalt;
        String token = request.getHeader(Keywords.TOKEN);

        if (StringUtils.isEmpty(token)) {
            throw new RuYiAdminCustomException(ExceptionMessage.InvalidTokenExceptionMessage);
        }

        token = RuYiRsaUtil.decrypt(token, this.systemConfig.getRsaPrivateKey());
        tokenSalt = StringUtils.split(token, "^")[1];

        return tokenSalt;
    }

    //endregion

}
